package com.anji.sp.schedule;

import com.anji.sp.service.SpAppLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.InetAddress;

/**
 * 定时任务类
 */

@Slf4j
@EnableScheduling
@Component
public class ScheduledLogTasks {
    @Value("${custom.app.jobId}")
    private String executeIp;

    /**
     * 是否可以执行任务
     */
    private Boolean canSchedule;

    @Autowired
    private SpAppLogService spAppLogService;

    /**
     * 备份app_sp_log表
     */
//    @Scheduled(cron = "30 * * * * ?")//测试(每30秒执行一次)
    @Scheduled(cron = "0 30 1 1 4,7,10,1 ?")//每三月1号凌晨一点半
    public void backupAppSpLop() {
        try {
            if (canPerformTask()) {
                log.info("sp_app_log表归档，每月1号将3个月前的那个月归档到sp_app_log_yyyyMM");
                spAppLogService.logTableArchive();
            }else {
                log.info("sp_app_log表归档，不是当前 ip  无法备份");
            }

        } catch (Exception e) {
            log.error("sp_app_log表归档异常", e);
        }
    }

    /**
     * 是否可以执行任务
     *
     * @return
     */
    private boolean canPerformTask() {
        if (canSchedule != null)
            return canSchedule;
        boolean result = false;
        try {
            log.info("executeIp:" + this.executeIp);
            InetAddress addr = InetAddress.getLocalHost();
            String localIp = addr.getHostAddress();
            log.info("localIp:" + localIp);
            if (executeIp.equals(localIp)) {
                canSchedule = true;
                return true;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
        canSchedule = false;
        return false;
    }


}
